<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_getUpgradeList"
    :columns="columns"
    row-key="dataManageId"
    :rowSelection="rowSelection"
  >
    <template #toolbars>
      <Space>
        <b-button icon="add" @click="onAdd()" code="dataManage:add"
          >新增</b-button
        >
        <b-button
          icon="delete"
          :disabled="!selectRows.length"
          @click="onDelete()"
          code="dataManage:remove"
          >删除
        </b-button>
      </Space>
    </template>
    <template #projectTreeSelects="{ record }">
      <Tree
        v-if="record.projectTreeSelects && record.projectTreeSelects.length"
        :tree-data="record.projectTreeSelects"
        :field-names="fileNames"
      />
      <!-- <span>{{ record.modelAlwaysVOS }}</span> -->
    </template>
    <template #operation="{ record }">
      <b-button icon="detail" type="link" @click="onDetail(record)"
        >详情</b-button
      >
      <template v-if="record.approveStatus != '2'">
        <b-button
          icon="examine"
          type="link"
          @click="onAudit(record)"
          code="dataManage:approve"
        >
          审核</b-button
        >
      </template>
      <template v-else>
        <b-button
          icon="remote"
          type="link"
          @click="handlePush(record)"
          code="dataPushTotalLog:add"
          >推送</b-button
        >
        <b-button
          icon="detail"
          type="link"
          @click="pushRecord(record)"
          code="dataPushTotalLog:query"
          >记录</b-button
        >
      </template>
    </template>
  </ProTable>
  <FormModal :items="items">
    <template #subType="{ formState }">
      <RadioGroup
        v-model:value="formState.subType"
        v-if="formState.deviceType == '1'"
      >
        <Radio v-for="item in terminaloptions" :value="item.value">{{
          item.label
        }}</Radio>
      </RadioGroup>
      <RadioGroup v-model:value="formState.subType" v-else>
        <Radio value="3">屏保图片</Radio>
      </RadioGroup>
    </template>
    <template #example="{ formState }">
      <img
        :width="200"
        v-if="formState.subType == '1'"
        src="@/assets/images/push/welcome.png"
      />
      <img
        :width="200"
        v-else-if="formState.subType == '2'"
        src="@/assets/images/push/front.png"
      />
      <img :width="200" v-else src="@/assets/images/push/screen.png" />
    </template>
    <!--   accept='.cer' -->
    <template #upload="{ formState }">
      <Upload
        :before-upload="onBeforeUpload"
        :custom-request="customRequest"
        :show-upload-list="false"
        :max-count="1"
        @change="onChange($event, formState)"
      >
        <img v-if="pictureHdfsName" class="w-[200px]" :src="uploadImg" />
        <div v-else>
          <Button :icon="h(UploadOutlined)">上传图片</Button>
          <p class="mt-2">支持图片格式：JPG、PNG、JPEG</p>
        </div>
      </Upload>
    </template>
  </FormModal>
  <Modal
    title="推送记录"
    v-model:open="pushRecordVisible"
    :width="1400"
    :mask-closable="false"
    :keyboard="false"
    :footer="null"
    centered
    destroy-on-close
  >
    <PushRecord :page-data="pageDate" @handleCheck="handleCheck" />
  </Modal>
  <Modal
    :title="failTitle"
    v-model:open="pushDeviceVisible"
    :width="1400"
    :mask-closable="false"
    :keyboard="false"
    :footer="null"
    centered
    destroy-on-close
  >
    <PushDevice :page-data="pushDeviceData" />
  </Modal>
  <Modal
    title="推送"
    v-model:open="pushConfigVisible"
    :width="1600"
    :mask-closable="false"
    :keyboard="false"
    :footer="null"
    centered
    destroy-on-close
  >
    <PushConfig
      :page-data="pageDate"
      @pushSuccess="pushSuccess"
      @close="pushConfigVisible = false"
    />
  </Modal>
  <Modal
    title="审核"
    v-model:open="pushAuditVisible"
    :width="1600"
    :mask-closable="false"
    :keyboard="false"
    centered
    destroy-on-close
  >
    <PushAudit :audit="pageDate" />
    <template #footer>
      <!--  -->
      <b-button @click="pushAuditVisible = false">关闭</b-button>
      <b-button
        v-if="pageDate.approveStatus != '2'"
        type="primary"
        @click="onAuditConfirm"
        >通过</b-button
      >
    </template>
  </Modal>
</template>

<script setup lang="tsx">
import { computed, h, onMounted, ref } from 'vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import {
  Button,
  Input,
  Modal,
  Radio,
  RadioGroup,
  Space,
  Tag,
  Tree,
  TreeProps,
  TreeSelect,
  Upload,
  type UploadChangeParam,
  type UploadProps,
  message,
} from 'ant-design-vue';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { download, hasOwnProperty, listToEnum } from '@/utils/utils';
import {
  deviceTypeEnum,
  deviceTypeOption,
  picUseTypeEnum,
} from '@/constant/push';
import { getProjectData } from '@/api/config';
import {
  addData,
  dataManageAprove,
  delData,
  getDataListInfo,
  idataManage,
  uploadFile,
} from '@/api/push';
import PushAudit from '../components/PushAudit.vue';
import PushConfig from '../components/PushConfig.vue';
import PushDevice from '../components/PushDevice.vue';
import PushRecord from '../components/PushRecord.vue';

const tableRef = ref();
const pageDate: any = ref({});
const failTitle: any = ref('');
const pushDeviceData: any = ref({});
const pushRecordVisible = ref(false);
const pushDeviceVisible = ref(false);
const deviceListVisible = ref(false);
const pushConfigVisible = ref(false);
const pushAuditVisible = ref(false);

const projectData = ref([]);
const auditEnum = {
  '2': '通过',
  '1': '待审核',
};

const selectRows = ref<any[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    onChange(values, selectedRows) {
      selectRows.value = selectedRows;
    },
  };
});
onMounted(() => {
  getProjectData().then((res: any) => {
    projectData.value = res.data;
  });
});
const fileNames: TreeProps['fieldNames'] = {
  title: 'label',
};
const _getUpgradeList = async (params: any) => {
  const res = await getDataListInfo({ ...params, type: '2' });
  return { rows: [...res.rows], total: res.total || 0 };
};

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '编码',
    dataIndex: 'dataCode',
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    valueEnum: deviceTypeEnum,
  },
  {
    title: '用途类型',
    dataIndex: 'subType',
    valueEnum: picUseTypeEnum,
  },
  {
    title: '所属项目',
    dataIndex: 'projectTreeSelects',
    hideInSearch: true,
  },
  {
    title: '所属项目',
    dataIndex: 'projectIds',
    hideInTable: true,
    customSearchRender(state) {
      return (
        <TreeSelect
          v-model:value={state.projectIds}
          fieldNames={{
            children: 'children',
            label: 'label',
            value: 'id',
          }}
          placeholder='请选择'
          treeData={projectData.value}
          allowClear={true}
        >
          {{
            title: ({ label, type }: any) => {
              return type == '1' ? (
                <span style='color:#bababa'>{label}</span>
              ) : (
                label
              );
            },
          }}
        </TreeSelect>
      );
    },
  },
  {
    title: '资料描述',
    dataIndex: 'dataDesc',
    hideInSearch: true,
  },
  {
    title: '发布次数',
    dataIndex: 'publishCount',
    hideInSearch: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    hideInSearch: true,
  },
  {
    title: '审核状态',
    dataIndex: 'approveStatus',
    hideInSearch: true,
    valueEnum: auditEnum,
    width: 100,
    customRender({ text }) {
      return (
        <Tag color={text == '2' ? 'success' : 'error'}>
          {auditEnum[text as keyof typeof auditEnum]}
        </Tag>
      );
    },
  },
  {
    title: '审核时间',
    dataIndex: 'approveTime',
    hideInSearch: true,
  },
  {
    title: '审核人',
    dataIndex: 'approveBy',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 300,
  },
]);
const terminaloptions = ref([
  { label: '首页图片', value: '1' },
  { label: '欢迎图片', value: '2' },
]);
const desktopoptions = ref([{ label: '屏保图片', value: '3' }]);
const items = computed<ProFormProps['items']>(() => [
  {
    label: '设备类型',
    type: 'radio',
    field: 'deviceType',
    rules: [
      {
        required: true,
        message: '请选择设备类型',
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请选择设备类型',
      options: deviceTypeOption,
      //       onChange(value: any, option) {
      // console.log(value)
      //       },
    },
  },
  {
    label: '所属项目',
    type: 'input',
    field: 'projectIds',
    rules: [
      {
        required: true,
        message: '请输入所属项目',
        trigger: 'blur',
      },
    ],
    customRender(formState) {
      return (
        <TreeSelect
          v-model:value={formState.projectIds}
          fieldNames={{
            children: 'children',
            label: 'label',
            value: 'id',
          }}
          placeholder='请选择'
          treeData={projectData.value}
          showCheckedStrategy={TreeSelect.SHOW_ALL}
          treeCheckable={true}
          maxTagCount={0}
          allowClear={true}
          maxTagPlaceholder={(omittedValues) => {
            if (omittedValues.length == 1) {
              return omittedValues[0].label;
            } else if (
              omittedValues.length == treeToArray(projectData.value).length
            ) {
              return '全部';
            } else {
              return '多项目';
            }
          }}
        >
          {{
            title: ({ label, type }: any) => {
              return type == '1' ? (
                <span style='color:#bababa'>{label}</span>
              ) : (
                label
              );
            },
          }}
        </TreeSelect>
      );
    },
  },
  {
    label: '用途类型',
    type: 'select',
    field: 'subType',
  },
  {
    label: '资料描述',
    type: 'textarea',
    field: 'dataDesc',
  },
  {
    label: '用途示例',
    type: 'input',
    field: 'example',
  },
  {
    label: '图片',
    type: 'input',
    field: 'upload',
    rules: [
      {
        required: true,
        message: '请上传图片',
        trigger: 'blur',
      },
    ],
  },
]);
const { FormModal, open, formRef } = useFormModal({
  size: 'middle',
  column: 2,
  formProps: { labelCol: { span: 4 } },
  onValuesChange(changeValues, formState) {
    if (hasOwnProperty(changeValues, 'deviceType')) {
      const { deviceType } = changeValues;
      if (deviceType == '3') {
        formState.subType = '3';
      } else {
        formState.subType = '1';
      }
    }
  },
});
const getBase64 = (img: Blob, callback: (base64Url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const pushRecord = (record: any) => {
  pageDate.value = record;
  pushRecordVisible.value = true;
};
const handlePush = (record: any) => {
  record.type = 1;
  pageDate.value = record;
  pushConfigVisible.value = true;
  pageDate.value.projectIds = treeToArray(record.projectTreeSelects);
};
const uploadImg = ref('');
const pictureHdfsName = ref('');
const pictureSourceName = ref('');
const onBeforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isPng =
    file.type === 'image/jpeg' ||
    file.type === 'image/png' ||
    file.type === 'image/jpg';
  if (!isPng) {
    message.error('上传仅支持图片格式JPG、PNG、JPEG');
  }
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    message.error('上传图片大小不能超过5MB!');
  }
  return isPng && isLt5M;
};
const onChange = (res: any, formState: any) => {
  if (res.file.status === 'done' && res.file.originFileObj) {
    pictureSourceName.value = res.file.name;
    getBase64(res.file.originFileObj, (base64Url: string) => {
      uploadImg.value = base64Url;
      formState.upload = res;
    });
  }
};
const handleCheck = (row: any, sta: any) => {
  pushDeviceData.value = row;
  if (sta == '0') {
    pushDeviceData.value.upgradeStatus = sta;
    failTitle.value = '推送失败设备列表';
  } else {
    pushDeviceData.value.upgradeStatus = '';
    failTitle.value = '推送设备列表';
  }
  pushDeviceVisible.value = true;
};

const pushSuccess = (row: any) => {
  sleep(() => tableRef.value.refresh());
  pushConfigVisible.value = false;
  pushDeviceData.value = row;
  failTitle.value = '推送结果';
  pushDeviceVisible.value = true;
};

const customRequest: UploadProps['customRequest'] = ({
  file,
  filename,
  onError,
  onSuccess,
  onProgress,
}) => {
  const formData = new FormData();
  formData.append('file', file);
  uploadFile(formData, {
    skipError: true,
    onUploadProgress: onProgress,
  })
    .then((res) => {
      // formRef.value.setFiledValue('publicKey', res.msg);
      pictureHdfsName.value = res.data.filename;
      onSuccess?.(res);
    })
    .catch((err) => {
      Modal.error({
        title: '提示',
        centered: true,
        content: err.message,
      });
      onError?.(err);
    });
};
const onAdd = async () => {
  pictureHdfsName.value = '';
  open({
    title: '新增',
    defaultValue: { deviceType: '1', subType: '1' },
    serviceApi: async (params: any): Promise<any> => {
      if (!pictureSourceName.value) {
        message.error('请上传图片');
        return Promise.reject();
      }
      await addData({
        ...params,
        pictureSourceName: pictureSourceName.value,
        pictureHdfsName: pictureHdfsName.value,
        projectIds: params.projectIds.join(','),
        type: '2',
      });
      sleep(() => tableRef.value.refresh());
    },
  });
};

const treeToArray = (treeArray: any) => {
  let ids: any = [];

  const traverseNode = (node: any) => {
    ids.push(node.id);

    if (node.children && Array.isArray(node.children)) {
      node.children.forEach((child: any) => traverseNode(child));
    }
  };

  treeArray.forEach((rootNode: any) => traverseNode(rootNode));

  return ids;
};

const onDetail = async (record: any) => {
  let response = await idataManage(record);
  pictureHdfsName.value = record.pictureHdfsName;
  uploadImg.value = 'data:image/png;base64,' + response;
  open({
    title: '详情',
    modalType: 'info',
    defaultValue: {
      ...record,
      projectIds: treeToArray(record.projectTreeSelects),
    },
    hasEditPermission: false,
    serviceApi: () => Promise.resolve(''),
  });
};

const onAuditConfirm = async (record: any) => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认审核通过？`,
    onOk: async () => {
      await dataManageAprove({
        dataManageId: pageDate.value.dataManageId,
        approveStatus: '2',
      });
      sleep(() => tableRef.value.refresh());
      pushAuditVisible.value = false;
      message.success('审核成功');
    },
  });
};
const onAudit = async (record: any) => {
  pushAuditVisible.value = true;
  pageDate.value = record;
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};

const onDelete = async () => {
  const dataManageIds = selectRows.value.map((item) => item.dataManageId);
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认删除当前项？`,
    onOk: async () => {
      await delData(dataManageIds.join());
      sleep(() => tableRef.value.refresh());
      message.success('删除成功');
    },
  });
};
</script>
